from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminUser import AdminUser
from masonite.facades import Session
from app.models.AdminUserLoginLog import AdminUserLoginLog
from masonite.facades import Cache
from app.my_package.MyPackage import MyValidator


class AuthController(Controller):
    uri = "/admin/user"
    temp = "admin.auth"
    title = "管理员登录"

    def getCaptcha(self):
        return ""

    def loginPage(self, view: View):
        data = {
            'title': "管理员-登录",
            'uri': self.uri,
        }
        return view.render(self.temp + ".login", data)

    def login(self, request: Request, response: Response, cache: Cache):
        account  = request.input("account")
        password = request.input("password")
        # captcha = request.input('captcha')

        b, m = MyValidator.alpha_num(account)
        if b is False:
            return response.json({'code': 0, 'message': '账户' + m})
        b, m = MyValidator.between(account, 2, 15)
        if b is False:
            return response.json({'code': 0, 'message': '账户' + m})
        b, m = MyValidator.alpha_num(password)
        if b is False:
            return response.json({'code': 0, 'message': '密码' + m})
        b, m = MyValidator.between(password, 5, 15)
        if b is False:
            return response.json({'code': 0, 'message': '密码' + m})

        admin_user = AdminUser.where("account", account).first()
        if admin_user is None:
            return response.json({'code': 0, 'message': f"账户 {account} 不存在"})

        if admin_user['password'] != MyModelTrait.generate_password(password, admin_user['salt']):
            return response.json({'code': 0, 'message': '密码错误'})

        AdminUserLoginLog.generate_log(admin_user.id, request.ip(), '登录')
        MyModelTrait.generate_login_session(admin_user)
        return response.json({'code': 1, 'message': '成功'})

    def logout(self, request: Request, response: Response):
        AdminUserLoginLog.generate_log(Session.get('admin_user')['id'], request.ip(), '登出')
        key = MyModelTrait.generate_cache_key(str(Session.get('admin_user')['id']))
        Cache.forget(key)
        Session.flush()

        return response.redirect(location = '/admin/user/login', status = 302)
